<?php

namespace App\Admin\Controllers\User;

use App\Admin\Controllers\Controller;
use App\Admin\Models\AdminRole;
use App\Admin\Models\AdminUser;
use Illuminate\Http\Request;

/**
 * Class UserController
 * @package App\Admin\Controllers
 *
 * 创建指定目录的控制器
 * @note: php artisan make:controller App\Admin\Controllers\UserController
 * @note: php artisan make:controller App\\Admin\\Controllers\\UserController
 */
class UserController extends Controller
{
    // 用户列表
    public function index()
    {
        $users = AdminUser::query()->paginate(10);
        return view('admin.user.index', compact('users'));
    }

    // 创建用户页面
    public function create()
    {
        return view('admin.user.create');
    }

    // 创建用户行为
    public function store(Request $request)
    {
        // 验证
        $rules = [
            'name' => 'required|string|min:2',
            'password' => 'required|string|between:5,20',
        ];
        $this->validate($request, $rules);

        // 保存
        $name = $request->input('name');
        $password = bcrypt($request->input('password'));

        AdminUser::query()->create(compact('name', 'password'));

        // 渲染
        return redirect('/admin/users');
    }

    // 用户角色页面
    public function roles(AdminUser $user)
    {
        // 所有的角色
        $roles = AdminRole::all();

        // 用户的角色
        $userRoles = $user->roles;

        return view('admin.user.roles', compact('roles', 'userRoles', 'user'));
    }

    // 用户角色行为
    public function storeRoles(Request $request, AdminUser $user)
    {
        $rules = [
            'roles' => 'required|array',
        ];
        $this->validate($request, $rules);

        $newRoles = AdminRole::query()->findMany($request->input('roles'));
        $oldRoles = $user->roles;

        // 要增加的
        $addRoles = $newRoles->diff($oldRoles);
        // 要删除的
        $deleteRoles = $oldRoles->diff($newRoles);
        info('storeRoles', [$addRoles, $deleteRoles]);
        foreach ($addRoles as $role) {
            $user->assignRole($role);
        }
        foreach ($deleteRoles as $role) {
            $user->deleteRole($role);
        }

        return redirect('/admin/users');
    }
    
}
